﻿using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace CommonManagement
{
    /// <summary>
    /// 积分应用服务类
    /// </summary>
    public class ScoreAppService : ApplicationService, IScoreAppService
    {
        private readonly IAuthManager _authManager;
        private readonly ScoreManager _scoreManager;
        private readonly IRepository<User, int> _userRepository;
        private readonly IRepository<Score, int> _scoreRepository;
        private readonly IRepository<Product, int> _productRepository;

        public ScoreAppService(
            JwtAuthManager authManager,
            ScoreManager scoreManager,
            IRepository<User, int> userRepository,
            IRepository<Score, int> scoreRepository,
            IRepository<Product, int> productRepository)
        {
            _authManager = authManager;
            _scoreManager = scoreManager;
            _userRepository = userRepository;
            _scoreRepository = scoreRepository;
            _productRepository = productRepository;
        }

        // 分页列表
        public async Task<ListResponse<ScoreDto>> PagedListAsync(PagedListRequest request)
        {
            // 查询
            var query = _scoreRepository
                .Include(m => m.User)
                .AsQueryable();
            // 计数
            var count = query.Count();
            // 排序
            if (!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Score>, List<ScoreDto>>(list);
            return ListResponse<ScoreDto>.Successful(count, dtos);
        }

        // 积分兑换
        [UnitOfWork]
        public async Task<ActionResponse> ConsumeAsync(int productId)
        {
            // 查询商品
            var product = await _productRepository.GetAsync(productId);
            // 查询用户积分
            var userId = _authManager.GetUserId();
            var user = await _userRepository.GetAsync(userId);
            // 减积分
            user.ScoreConsume(product.Score);
            // 积分记录
            await _scoreManager.CreateAsync(userId, ScoreEvent.兑换商品, product.Score, ScoreChangeType.扣除);
            // 返回结果
            return ActionResponse.Successful();
        }

        // 积分排行榜
        public async Task<ListResponse<TopDto>> TopListAsync()
        {
            // 查询积分前三用户
            var users = await _userRepository
                .OrderByDescending(m => m.Score)
                .Take(3)
                .ToListAsync();
            // entity转dto
            var dtos = ObjectMapper.Map<List<User>, List<TopDto>>(users);
            for (int i = 0; i < dtos.Count; i++)
            {
                dtos[i].DeptId = null;
                dtos[i].Salt = null;
                dtos[i].Status = "0";
                dtos[i].DelFlag = "0";
                dtos[i].LoginIp = "";
                dtos[i].LoginDate = null;
                dtos[i].Roles = new List<string>();
                dtos[i].RoleIds = null;
                dtos[i].PostIds = null;
                dtos[i].Admin = false;
            }
            // 返回结果
            return ListResponse<TopDto>.Successful(dtos.Count, dtos);
        }
    }
}